﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CtCommon.Utility;
using Cxx.BLL;
using Cxx.Common;
using Cxx.Entity;

namespace Cxx.OrderManagerSys
{
    public partial class OrderDetail : System.Web.UI.Page
    {
        /// <summary>
        /// 明细json
        /// </summary>
        public string DetailJson;

        /// <summary>
        /// 订单ID
        /// </summary>
        private int orderId;

        protected void Page_Load(object sender, EventArgs e)
        {
            orderId = WebHelper.GetQueryInt("orderId");
            if (!Page.IsPostBack)
            {
                
                DataInit();
            }
        }

        /// <summary>
        /// 数据初始化
        /// </summary>
        private void DataInit()
        {
            if (orderId == 0)
            {
                btModify.Visible = false;
                return;
            }
            btSave.Visible = false;
            OrderInfo info = Order.Get(orderId);
            if (info == null)
            {
                txtOrderCode.Msg("订单不存在");
                return;
            }
            if (!string.IsNullOrWhiteSpace(info.Detail))
            {
                var details = info.Detail.JSONDeserialize<List<DetailInfo>>();
                details.ForEach(p =>
                {
                    if (string.IsNullOrWhiteSpace(p.Times))
                    {
                        p.Times = "1";
                    }
                });
                info.Detail = details.JSONSerialize();
                DetailJson = info.Detail;
            }
            txtOrderCode.Text = info.OrderCode;
            txtDateTime.Text = info.Time.ToString("yyyy-MM-dd HH:mm:ss");
            txtCustomer.Text = info.Receiver;
            ckPaymented.Checked = info.Paymented;
            ckHasOrder.Checked = info.HasOrder;
            txtTotalAmount.Text = info.Amount.ToString();
            txtAttention.Text = info.Remark;
        }

        protected void Save_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtOrderCode.Text))
            {
                txtOrderCode.Msg("请输入单号");
                return;
            }
            OrderInfo info = new OrderInfo
            {
                OrderCode = txtOrderCode.Text,
                Time = txtDateTime.Text.ToDateTime("yyyy-MM-dd HH:mm:ss"),
                Paymented = WebHelper.GetFormString("ckPaymented") == "on",
                HasOrder = WebHelper.GetFormString("ckHasOrder") == "on",
                Receiver = txtCustomer.Text,
                Remark = txtAttention.Text,
                Amount = 0,
                Detail = string.Empty
            };
            if (!string.IsNullOrWhiteSpace(getData.Value))
            {
                info.DetailInfos = getData.Value.JSONDeserialize<List<DetailInfo>>();
                info.DetailInfos.ForEach(p =>
                {
                    if (string.IsNullOrWhiteSpace(p.Times) || p.Times == "0")
                    {
                        p.Times = "1";
                    }
                });
                foreach (var p in info.DetailInfos)
                {
                    p.Total = Rounding(p.Count.ToDouble(), p.UnitPrice.ToDouble(), p.Times.ToDouble())
                        .ToString(CultureInfo.InvariantCulture);
                    int usingCount = p.Times.ToInt32() * p.Count.ToInt32();
                    StockInfo stockInfo = Stock.Get(info.Receiver, p.Name);
                    if (stockInfo == null)
                    {
                        continue;
                    }
                    stockInfo.TotalCount = stockInfo.TotalCount - usingCount;
                    Stock.Update(stockInfo);

                    StockRecordInfo stockRecordInfo = new StockRecordInfo
                    {
                        CreateTime = DateTime.Now,
                        OrderCode = info.OrderCode,
                        Receiver = info.Receiver,
                        StockType = (int) StockTypes.Out,
                        TotalCount = usingCount,
                        TradeName = p.Name,
                        StockCode = ""
                    };
                    StockRecord.Insert(stockRecordInfo);
                }
                info.Amount = info.DetailInfos.Sum(p => p.Total.ToInt32());
                info.Detail = info.DetailInfos.JSONSerialize();
            }
            Order.Insert(info);
            JScript.Alert(Page, "添加完成", $"window.parent.location.href='http://{Request.Url.Host}:{Request.Url.Port}/OrderList.aspx';parent.layer.close(index);");
        }

        private double Rounding(double count, double unitPrice, double times)
        {
            var temp = count * unitPrice * times;
            return Math.Round(temp, MidpointRounding.AwayFromZero);
        }
        protected void btModify_Click(object sender, EventArgs e)
        {
            OrderInfo info = Order.Get(orderId);
            if (info == null)
            {
                txtOrderCode.Msg("订单不存在");
                return;
            }
            if (string.IsNullOrWhiteSpace(txtOrderCode.Text))
            {
                txtOrderCode.Msg("请输入单号");
                return;
            }
            info.OrderCode = WebHelper.GetFormString("txtOrderCode");
            info.Time = WebHelper.GetFormString("txtDateTime").ToDateTime("yyyy-MM-dd HH:mm:ss");
            info.Paymented = WebHelper.GetFormString("ckPaymented") == "on";
            info.HasOrder = WebHelper.GetFormString("ckHasOrder") == "on";
            info.Receiver = WebHelper.GetFormString("txtCustomer");
            info.Remark = WebHelper.GetFormString("txtAttention");
            var oldDetails = info.Detail?.JSONDeserialize<List<DetailInfo>>() ?? new List<DetailInfo>();
            if (!string.IsNullOrWhiteSpace(getData.Value))
            {
                info.DetailInfos = getData.Value.JSONDeserialize<List<DetailInfo>>();
                info.DetailInfos.ForEach(p =>
                {
                    if (string.IsNullOrWhiteSpace(p.Times) || p.Times == "0")
                    {
                        p.Times = "1";
                    }
                });
                foreach (var p in info.DetailInfos)
                {
                    StockInfo stockInfo = Stock.Get(info.Receiver, p.Name);
                    if (stockInfo == null)
                    {
                        continue;
                    }

                    var usingCount = p.Times.ToInt32() * p.Count.ToInt32();
                    var detailInfo = oldDetails.Find(o => o.Name == p.Name);
                    if (detailInfo == null)
                    {
                        stockInfo.TotalCount = stockInfo.TotalCount - usingCount;
                        StockRecordInfo stockRecordInfo = new StockRecordInfo
                        {
                            CreateTime = DateTime.Now,
                            OrderCode = info.OrderCode,
                            Receiver = info.Receiver,
                            StockType = (int) StockTypes.Out,
                            TotalCount = usingCount,
                            TradeName = p.Name,
                            StockCode = ""
                        };
                        StockRecord.Insert(stockRecordInfo);
                    }
                    else
                    {
                        //var countNow = p.Times.ToInt32() * p.Count.ToInt32();
                        var countOld = detailInfo.Count.ToInt32() * detailInfo.Times.ToInt32();
                        var change = usingCount - countOld;
                        stockInfo.TotalCount = stockInfo.TotalCount - change;
                        if (change != 0)
                        {
                            StockRecordInfo stockRecordInfo = new StockRecordInfo
                            {
                                CreateTime = DateTime.Now,
                                OrderCode = info.OrderCode,
                                Receiver = info.Receiver,
                                StockType = change > 0 ? (int) StockTypes.Out : (int) StockTypes.Rollback,
                                TotalCount = Math.Abs(change),
                                TradeName = p.Name,
                                StockCode = ""
                            };
                            StockRecord.Insert(stockRecordInfo);
                        }
                    }
                    Stock.Update(stockInfo);
                }

                foreach (var p in info.DetailInfos)
                {
                    if (p.Total.ToInt32() != 0)
                    {
                        continue;
                    }
                    p.Total = Rounding(p.Count.ToDouble(), p.UnitPrice.ToDouble(), p.Times.ToDouble())
                        .ToString(CultureInfo.InvariantCulture);
                }

                info.Amount = string.IsNullOrWhiteSpace(WebHelper.GetFormString("txtTotalAmount"))
                    ? info.DetailInfos.Sum(p => p.Total.ToInt32())
                    : WebHelper.GetFromInt("txtTotalAmount");
                info.Detail = info.DetailInfos.JSONSerialize();
            }
            Order.Update(info);
            JScript.Alert(Page, "修改完成", $"window.parent.location.href='http://{Request.Url.Host}:{Request.Url.Port}/OrderList.aspx';parent.layer.close(index);");
        }
    }
}